#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
//    modebus = new ModbusServer(3);
//    modebus->startSerialServer("COM1",9600,1);
//    modebus->setHoldingRegister(3,100);
//    modebus->setFloatHoldingRegister(4,123.345);
    modebus_tcp = new ModbusServer();
    modebus_tcp->startTcpServer("127.0.0.1",506,1);
    modebus_tcp->setHoldingRegister(3,100);
    modebus_tcp->setFloatHoldingRegister(4,123.345);
    modbus_clent = new ModbusClient();
    modbus_clent->init(ModbusMode::TCP,"127.0.0.1",502);
    tcpServer = new TcpServer(this);
    tcpServer->startServer(9999);
    tcpClient = new TcpClient(this);
    tcpClient->connectToServer("127.0.0.1",8080);
    udpsocek = new UdpSocket(this);
    udpsocek->bindPort(9090);
    tip.bindLabel(ui->label);
    QTimer  * timer = new QTimer(this);
       connect(timer, &QTimer::timeout, [=]() {
           static int i  = 0;
          double me = m_memorMoitor.getCurrentMemoryUsageMB();
          ui->label_2->setText(QString("内存使用: %1 MB").arg(me));
            //m_modbusClient_dev.write_int(1,i++);
          LOG_DEBUG<<"运行一次任务";
            m_modbusClient_dev.read_registers(1,10);

       });

       timer->start(1000);  // 每 1 秒调用一次
       m_modbusClient.init(ModbusMode::TCP,"127.0.0.1",502);
       m_modbusClient_dev.setDeviceId(1);
       m_modbusmanger.register_dev_client(&m_modbusClient_dev,&m_modbusClient);
       QVector<int> v{1, 2, 3, 4};
       try {
           LOG_DEBUG<< v.value(10,-99999);   // 访问第 101 个元素
       }
       catch (const std::out_of_range& e) {
           // 打印具体异常信息
           LOG_DEBUG << "Index out of range while accessing QVector: " << e.what();
           // 这里可以做自己的处理，比如返回一个默认值或发出信号
           // emit dataError("Index 100 is out of range");
       }

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    static int i =0;
    modebus_tcp->setFloatHoldingRegister(4,13.345);
    modbus_clent->sendTestComand();
    tcpServer->sendDataToAllClients("你好 看完了丘吉尔");
    tcpClient->sendData("你好 看完了丘吉尔");
    udpsocek->sendData(QHostAddress("127.0.0.1"),8080,"swqewqesdwqe");
    tip.setTooltip(QString("你好,这是我的提示%1").arg(i++));
}

void MainWindow::on_pushButton_2_clicked()
{
    LOG_DEBUG<<"发送指令,延时3秒";
    pauseProcess(3000);
    LOG_DEBUG<<"发送指令,延时3秒 结束";
}


